package org.alfresco.custom.repo.web.scripts.workflow;

import javax.servlet.http.HttpServletResponse;

import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.AuthorityService;
import org.alfresco.service.cmr.workflow.WorkflowTask;
import org.springframework.extensions.webscripts.WebScriptException;
import org.springframework.extensions.webscripts.WebScriptRequest;

/**
 * 
 * @author Rui Fernandes
 * 
 */
public class WorkflowWebscriptAuthorityCheck {

	public static final String PARAM_AUTHORITY = "authority";

	private WorkflowWebscriptAuthorityCheck() {
	}

	public static String getAuthority(WebScriptRequest req) {
		String authority = req.getParameter(PARAM_AUTHORITY);
		if (authority == null || authority.length() == 0) {
			authority = null;
		}
		return authority;
	}

	public static void assertUserAdminOrProperAuthority(
			AuthenticationService authenticationService,
			AuthorityService authorityService, WorkflowTask workflowTask) {
		String user = authenticationService.getCurrentUserName();
		if (!authorityService.isAdminAuthority(user)) {
			String authority = (String) workflowTask.getProperties().get(
					ContentModel.PROP_OWNER);
			if (authority == null || !authority.equals(user)) {
				String msg = String
						.format("Not allowed to access task: %s",
								workflowTask.getId());
				throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN,
						msg);
			}
		}
	}
	
	
	public static void assertUserAdminOrProperAuthority(
			AuthenticationService authenticationService,
			AuthorityService authorityService,WebScriptRequest req ) {
		String user = authenticationService.getCurrentUserName();
		if (!authorityService.isAdminAuthority(user)) {
			String authority= getAuthority(req);
			if (authority == null || !authority.equals(user)) {
				String msg = String
						.format("Not allowed to access task information for authority: %s",
								authority);
				throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN,
						msg);
			}
		}
	}

}